<template>
  <view class="container">
    <!-- 倒计时组件 -->
    <view class="countdown-container" :class="isExpired ? 'expired' : ''">
      <view class="countdown-icon">
        <uni-icons type="clock" size="24" color="#fff"></uni-icons>
      </view>
      <text class="countdown-text">支付剩余时间：</text>
      <text class="countdown-time">{{ countdown }}</text>
      <text class="countdown-expired" v-if="isExpired">已超时</text>
    </view>

    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">订单确认</text>
    </view>

    <!-- 订单信息 -->
    <view class="order-info" v-if="orderInfo">
      <view class="info-item">
        <text class="label">订单号：</text>
        <text class="value">{{ orderInfo.orderNumber || 'N/A' }}</text>
      </view>
      <view class="info-item">
        <text class="label">商品名称：</text>
        <text class="value">{{ orderInfo.itemName || '未命名商品' }}</text>
      </view>
      <view class="info-item">
        <text class="label">订单金额：</text>
        <text class="value price">¥{{ orderInfo.totalAmount || '0.00' }}</text>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="payment-section">
      <text class="section-title">支付方式</text>
      <radio-group @change="handlePaymentChange">
        <label class="payment-option">
          <radio value="3" :checked="paymentMethod === '3'" :disabled="isExpired" />
          <text>钱包支付</text>
          <text class="balance" v-if="paymentMethod === '3'">(余额: ¥{{ walletBalance }})</text>
        </label>
        <label class="payment-option">
          <radio value="1" :checked="paymentMethod === '1'" :disabled="isExpired" />
          <text>支付宝支付</text>
        </label>
        <label class="payment-option">
          <radio value="2" :checked="paymentMethod === '2'" :disabled="isExpired" />
          <text>微信支付</text>
        </label>
      </radio-group>
    </view>

    <!-- 支付按钮 -->
    <view class="pay-btn-container">
      <button class="pay-btn" @click="handlePayment" :disabled="isPaying || isExpired">
        {{ isPaying ? '支付中...' : (isExpired ? '订单已超时' : '确认支付') }}
      </button>
    </view>

    <!-- 加载状态 -->
    <uni-load-more v-if="isLoading" status="loading" :contentText="loadingText"></uni-load-more>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {
  getBalance,
  payByWallet,
  payByAlipay,
  payByWechat,
  selectOrder,
} from "@/apis/orderApi";

// 订单信息
const orderInfo = ref({
  orderId: '',
  orderNumber: '',
  itemName: '',
  totalAmount: '',
  orderPrice: '',
  userId: '',
  nickName: '',
  expireTime: '' // 添加expireTime字段
});

// 获取用户信息（从缓存中）
const userInfo = uni.getStorageSync('userInfo') || {}; // 确保不为null
console.log('用户信息:', userInfo); // 调试：查看是否有balance字段

// 钱包余额（修正字段名拼写，添加默认值0，用ref响应式）
const walletBalance = ref((userInfo.balance || 0).toFixed(2)); // 保留两位小数

// 支付方式
const paymentMethod = ref('3');

// 加载状态
const isLoading = ref(false);
const isPaying = ref(false);
const loadingText = ref({
  contentdown: '下拉显示更多',
  contentrefresh: '加载中',
  contentnomore: '没有更多数据'
});

// 倒计时相关
const countdown = ref('00:00:00'); // 格式改为HH:MM:SS
const expireTime = ref(0); // 后端返回的过期时间戳（毫秒）
const timer = ref(null);
const isExpired = ref(false);

// 页面加载时获取订单信息和倒计时
onLoad((options) => {
  console.log('页面加载参数:', options);
  if (options.orderId) {
    orderInfo.value.orderId = options.orderId;
    console.log('订单ID:', options.orderId);
    orderInfo.value.orderNumber = options.orderNumber || '';
    // 获取订单信息（包含expireTime）
    fetchOrderInfo(options.orderId).catch(error => {
      console.error('页面加载失败:', error);
      uni.showToast({ title: '加载订单信息失败', icon: 'none' });
    });
  } else {
    uni.showToast({ title: '缺少订单ID', icon: 'none' });
  }
});

onMounted(() => {
  // 补充：主动获取最新余额（避免缓存过期）
  fetchLatestBalance();
});

onUnmounted(() => {
  // 清除定时器
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 主动获取最新余额（优化：避免缓存过期）
const fetchLatestBalance = async () => {
  if (!userInfo.userId) return; // 没有用户ID则不请求
  try {
    const res = await getBalance(userInfo.userId);
    if (res.data.code === 200) {
      // 更新余额（保留两位小数）
      walletBalance.value = (res.data.data.balance || 0).toFixed(2);
    }
  } catch (error) {
    console.error('获取最新余额失败:', error);
    // 失败不影响，继续使用缓存值
  }
};

// 获取订单信息（包含expireTime）
const fetchOrderInfo = async (orderId) => {
  console.log('获取订单信息:', orderId);
  try {
    isLoading.value = true;
    const res = await selectOrder(orderId);
    console.log('订单信息响应:', res);
    if (res.data && res.data.code === 200) {
      orderInfo.value = { ...orderInfo.value, ...res.data.data };

      // 从后端数据中提取expireTime并转换为时间戳
      if (res.data.data.expireTime) {
        expireTime.value = new Date(res.data.data.expireTime).getTime();
        console.log('后端返回的过期时间:', new Date(expireTime.value).toLocaleString());
        startCountdown();
      } else {
        // 若后端未返回过期时间，默认15分钟
        console.warn('后端未返回expireTime，使用默认值');
        const now = new Date();
        expireTime.value = now.getTime() + 15 * 60 * 1000;
        startCountdown();
      }
    } else {
      uni.showToast({ title: res.data.message || '获取订单信息失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取订单信息失败:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  // 立即更新一次倒计时
  updateCountdown();

  // 每秒更新一次
  timer.value = setInterval(() => {
    updateCountdown();
  }, 1000);
};

// 更新倒计时显示（精确到时分秒）
const updateCountdown = () => {
  const now = new Date().getTime(); // 当前时间戳（毫秒）
  const diff = expireTime.value - now; // 剩余时间（毫秒）

  if (diff <= 0) {
    // 倒计时结束
    countdown.value = '00:00:00';
    isExpired.value = true;
    clearInterval(timer.value); // 清除定时器
    return;
  }

  // 计算时、分、秒
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  // 格式化显示（补零）
  countdown.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 处理支付方式变更
const handlePaymentChange = (e) => {
  paymentMethod.value = e.detail.value;
  console.log('选择的支付方式:', paymentMethod.value);
};

// 处理支付
const handlePayment = async () => {
  if (isExpired.value) {
    uni.showToast({ title: '订单已超时，请重新下单', icon: 'none' });
    return;
  }

  try {
    const paymentData = {
      orderId: orderInfo.value.orderId,
      orderPrice: orderInfo.value.totalAmount,
      orderNumber: orderInfo.value.orderNumber,
      idleItemId: orderInfo.value.itemId,
      userId: userInfo.userId,
    };
    console.log('支付请求数据:', paymentData);

    isPaying.value = true;

    // 根据支付方式调用不同接口
    switch (paymentMethod.value) {
      case '3': // 钱包支付
        await handleWalletPayment(paymentData);
        break;
      case '1': // 支付宝支付
        await handleAlipayPayment(paymentData);
        break;
      case '2': // 微信支付
        await handleWechatPayment(paymentData);
        break;
      default:
        throw new Error('不支持的支付方式');
    }
  } catch (error) {
    console.error('支付错误:', error);
    uni.showToast({
      title: error.message || '支付请求失败，请重试',
      icon: 'none'
    });
  } finally {
    isPaying.value = false;
  }
};

// 钱包支付处理
const handleWalletPayment = async (paymentData) => {
  // 再次检查余额（使用最新值）
  const balanceNum = parseFloat(walletBalance.value);
  const orderPriceNum = parseFloat(paymentData.orderPrice);

  if (balanceNum < orderPriceNum) {
    throw new Error('钱包余额不足');
  }

  // 调用钱包支付API
  const res = await payByWallet(paymentData);
  if (res.data && res.data.code === 200) {
    uni.showToast({ title: '支付成功', icon: 'success' });
    // 支付成功后更新本地余额
    walletBalance.value = (balanceNum - orderPriceNum).toFixed(2);
    // 跳转订单列表
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/myOrder/myOrder' });
    }, 1500);
  } else {
    throw new Error(res.data.message || '支付失败');
  }
};

// 支付宝支付处理
const handleAlipayPayment = async (paymentData) => {
  const res = await payByAlipay(paymentData);
  console.log('支付宝支付响应:', res.data);

  const { qrCode, outTradeNo } = res.data;

  // 跳转支付宝页面
  uni.navigateTo({
    url: `/pages/shop/alipay?qrCode=${encodeURIComponent(qrCode)}&outTradeNo=${encodeURIComponent(outTradeNo)}&amount=${paymentData.orderPrice}`
  });
};

// 微信支付处理
const handleWechatPayment = async (paymentData) => {
  const res = await payByWechat(paymentData);

  if (res.data && res.data.code === 200) {
    const wechatParams = res.data.data;

    // 调起微信支付
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: wechatParams.timeStamp,
      nonceStr: wechatParams.nonceStr,
      package: wechatParams.package,
      signType: wechatParams.signType,
      paySign: wechatParams.paySign,
      success: (res) => {
        uni.showToast({ title: '支付成功', icon: 'success' });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      },
      fail: (err) => {
        throw new Error('用户取消支付或支付失败');
      }
    });
  } else {
    throw new Error(res.data.message || '获取微信支付信息失败');
  }
};

// 返回上一页
const goBack = () => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  uni.navigateBack();
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.countdown-container {
  display: flex;
  align-items: center;
  background-color: #ff4544;
  color: #fff;
  padding: 15rpx 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.countdown-icon {
  margin-right: 10rpx;
}

.countdown-text {
  margin-right: 10rpx;
}

.countdown-time {
  font-weight: bold;
}

.countdown-expired {
  color: #ffcccc;
  margin-left: 10rpx;
}

.expired {
  background-color: #999;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 0;
  padding: 10rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

.order-info {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  font-size: 32rpx;
}

.label {
  color: #666;
  width: 160rpx;
}

.value {
  flex: 1;
  color: #333;
}

.price {
  color: #e64340;
  font-weight: bold;
}

.payment-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  display: block;
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  font-size: 32rpx;
}

.payment-option:last-child {
  border-bottom: none;
}

.balance {
  margin-left: 10rpx;
  color: #888;
  font-size: 28rpx;
}

.pay-btn-container {
  margin-top: 40rpx;
  padding: 0 30rpx;
}

.pay-btn {
  background-color: #07c160;
  color: #fff;
  border-radius: 50rpx;
  font-size: 34rpx;
  height: 90rpx;
  line-height: 90rpx;
}

.pay-btn[disabled] {
  background-color: #ccc;
}
</style>